package com.demo;

/*
CompletableFuture实现异步回调
 */

import java.util.concurrent.CompletableFuture;
import java.util.function.Consumer;
import java.util.function.Supplier;

class Demo12Hello implements Supplier<String> {
    @Override
    public String get() {
        return "Hello ";
    }
}

class Demo12Complete implements Consumer<Object> {
    @Override
    public void accept(Object s) {
        System.out.println("最终结果 = " + s);
    }
}
public class Demo12 {
    public static void main(String[] args) {
        // 面向对象写法
        CompletableFuture<String> future1 = CompletableFuture.supplyAsync(new Demo12Hello());

        // lambda简化写法
        CompletableFuture<String> future2 = CompletableFuture.supplyAsync(() -> {
            return "你好 ";
        });

        CompletableFuture<Object> future = CompletableFuture.anyOf(future1, future2);

        CompletableFuture<String> world1 = future.thenApplyAsync((prefix) -> {
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            return prefix + "World";
        });

        CompletableFuture<String> world2 = future.thenApplyAsync((prefix) -> {
            return prefix + "世界";
        });

        CompletableFuture<Object> complete = CompletableFuture.anyOf(world1, world2);

        /**
         * 运行过程就是future1、future2并行执行，任一执行完毕后并行执行world1、world2
         * 最终将两段字符串随机拼接
         */
        complete.thenAccept(new Demo12Complete());
    }
}
